package server.scripting.npc;

/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 * NPCScriptManager.java
 *
 * Steven Louie Apr. 8, 2012
 *
 */
import client.ActinoClient;
import client.ActinoPlayer;
import java.util.HashMap;
import javax.script.Invocable;
import server.scripting.AbstractScriptManager;

public class NPCScriptManager extends AbstractScriptManager {

    private HashMap<ActinoClient, NPCConversationManager> cms = new HashMap<>();
    private HashMap<ActinoClient, NPCScript> scripts = new HashMap<>();
    private static NPCScriptManager instance = new NPCScriptManager();

    public synchronized static NPCScriptManager getInstance() {
        return instance;
    }

    public void start(ActinoClient c, int npc) {
        start(c, npc, null, null);
    }

    public void start(ActinoClient c, int npc, String filename, ActinoPlayer chr) {
        try {
            NPCConversationManager cm = new NPCConversationManager(c, npc, chr, filename);
            if (cms.containsKey(c)) {
                dispose(c);
                return;
            }
            cms.put(c, cm);
            Invocable iv = getInvocable("npc/" + npc + ".js", c);
            if (filename != null) {
                iv = getInvocable("npc/" + filename + ".js", c);
            }
            if (iv == null || NPCScriptManager.getInstance() == null) {
                if (iv == null) {
                    System.out.println("Hi I'm an uncoded npc. My ID is " + npc + ".");
                }
                cm.dispose();
                return;
            }
            engine.put("cm", cm);
            NPCScript ns = iv.getInterface(NPCScript.class);
            scripts.put(c, ns);
            ns.start();
        } catch (Exception e) {
            dispose(c);
            System.out.println("NPC Error: " + npc);
        }
    }

    public void action(ActinoClient c, byte mode, byte type, int selection) {
        NPCScript ns = scripts.get(c);
    }

    public NPCConversationManager getCM(ActinoClient c) {
        return cms.get(c);
    }

    public void dispose(ActinoClient c) {
        if (cms.get(c) != null) {
            dispose(cms.get(c));
        }
    }

    public void dispose(NPCConversationManager cm) {
        ActinoClient c = cm.getClient();
        cms.remove(c);
        scripts.remove(c);
    }
}
